package com.ibeeking.found.cms.b.rest.service.impl;

import com.ibeeking.found.cms.b.rest.service.IPageBaseService;
import com.ibeeking.found.cms.b.rest.service.IPageModuleService;
import com.ibeeking.found.cms.b.rest.service.IPageTemplateBaseService;
import com.ibeeking.found.cms.b.rest.service.IPageTemplateModuleService;
import com.ibeeking.found.cms.service.common.bo.PageBaseBO;
import com.ibeeking.found.cms.service.common.bo.PageTemplateBaseBO;
import com.ibeeking.found.cms.service.common.bo.PageTemplateModuleBO;
import com.ibeeking.found.cms.service.common.constants.enums.PageCategoryEnum;
import com.ibeeking.found.cms.service.common.constants.enums.PagePublishStatusEnum;
import com.ibeeking.found.cms.service.common.dos.PageModuleDO;
import com.ibeeking.found.cms.service.common.dos.PageTemplateBaseDO;
import com.ibeeking.found.cms.service.common.param.*;
import com.ibeeking.found.cms.service.common.query.PageBasePageQuery;
import com.ibeeking.found.cms.service.common.query.PageBaseQuery;
import com.ibeeking.found.cms.service.common.vo.PageBaseVO;
import com.ibeeking.found.cms.service.mapper.PageTemplateBaseMapper;
import com.ibeeking.found.common.config.prop.FileOssProp;
import com.ibeeking.found.common.constants.DefaultPathConstant;
import com.ibeeking.found.common.constants.GlobalConstant;
import com.ibeeking.found.common.entity.CurrentUser;
import com.ibeeking.found.common.enums.cms.PageTemplateTypeEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.UrlUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.id.IdGenerator;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @ClassName PageBaseServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-05-08 16:05
 **/
@Service
public class PageTemplateBaseServiceImpl extends ServiceImpl<PageTemplateBaseMapper, PageTemplateBaseDO> implements IPageTemplateBaseService {

    @Resource
    private PageTemplateBaseMapper pageTemplateBaseMapper;
    @Resource
    private IPageTemplateModuleService pageTemplateModuleServiceImpl;
    @Resource
    private IPageBaseService pageBaseServiceImpl;
    @Resource
    private IPageModuleService pageModuleServiceImpl;
    @Resource
    private FileOssProp fileOssProp;


    @Override
    public List<PageBaseVO> list(PageBaseQuery query) {
        List<PageTemplateBaseDO> pageBaseDOs = pageTemplateBaseMapper.selectList(new LambdaQueryWrapper<PageTemplateBaseDO>());
        return JsonUtils.jsonToList(pageBaseDOs, PageBaseVO.class);
    }

    @Override
    public Page<PageBaseVO> pageList(PageBasePageQuery pageQuery, CurrentUser currentUser) {
        if(pageQuery.getFeebackBlank() > 0 && pageQuery.getPageNum() == 1){
            pageQuery.setPageSize(pageQuery.getPageSize() - 1);
        }
        LambdaQueryWrapper<PageTemplateBaseDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(pageQuery.getPlatform() != null, PageTemplateBaseDO::getPlatform, pageQuery.getPlatform());
        queryWrapper.eq(pageQuery.getPublishStatus() != null, PageTemplateBaseDO::getPublishStatus, pageQuery.getPublishStatus());
        queryWrapper.eq(pageQuery.getShopId() != null, PageTemplateBaseDO::getShopId, pageQuery.getShopId());
        queryWrapper.eq(pageQuery.getTemplateType() != null, PageTemplateBaseDO::getTemplateType, pageQuery.getTemplateType());
        queryWrapper.like(StringUtils.isNotBlank(pageQuery.getTitle()), PageTemplateBaseDO::getTitle, pageQuery.getTitle());
        Page<PageTemplateBaseDO> pages = pageTemplateBaseMapper.selectPage(new Page<PageTemplateBaseDO>(pageQuery.getPageNum(), pageQuery.getPageSize()), queryWrapper);
        Page<PageBaseVO> pageBaseVOPage = BeanUtil.convertPage(pages, PageBaseVO.class);
        List<PageBaseVO> records = pageBaseVOPage.getRecords();
        if(pageQuery.getFeebackBlank() > 0 && pageQuery.getPageNum() == 1){
            PageBaseVO blankPageVO = new PageBaseVO();
            blankPageVO.setId(Long.valueOf(GlobalConstant.tenantId));
            blankPageVO.setTemplateName(GlobalConstant.BLANK);
            blankPageVO.setTemplateImgUrl(DefaultPathConstant.DEFAULT_CMS_BLANK_TEMPLATE);
            blankPageVO.setPublishStatus(PagePublishStatusEnum.YES.getValue());
            if(Collections3.isEmpty(records))
                records = new ArrayList<>();
            records.add(blankPageVO);
        }
        Optional.ofNullable(records).ifPresent(list -> {
            list.stream().sorted(Comparator.comparing(PageBaseVO::getId, Comparator.reverseOrder())).forEach(x -> {
                x.setPublishStatusName(PagePublishStatusEnum.getName(x.getPublishStatus()));
                x.setTemplateImgUrl(UrlUtils.addUrlDomainName(fileOssProp.getHost(), x.getTemplateImgUrl()));
            });
        });
        return pageBaseVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long add(PageTemplateBaseParam pageTemplateBaseParam) {
        PageTemplateBaseDO pageTemplateBaseDO = BeanUtil.convertBean(pageTemplateBaseParam, PageTemplateBaseDO.class);
        if(StringUtils.isEmpty(pageTemplateBaseParam.getIndustry())){
            pageTemplateBaseDO.setIndustry(UserUtils.getTenantIndustry());
        }
        pageTemplateBaseDO.setCreateBy(UserUtils.getUserId());
        pageTemplateBaseDO.setCreateTime(LocalDateTime.now());
        pageTemplateBaseDO.setModifyTime(LocalDateTime.now());
        pageTemplateBaseMapper.insert(pageTemplateBaseDO);
        return pageTemplateBaseDO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long modify(PageTemplateBaseParam pageTemplateBaseParam) {
        PageTemplateBaseDO pageTemplateBaseDO = BeanUtil.convertBean(pageTemplateBaseParam, PageTemplateBaseDO.class);
        if(StringUtils.isEmpty(pageTemplateBaseParam.getIndustry())){
            pageTemplateBaseDO.setIndustry(UserUtils.getTenantIndustry());
        }
        pageTemplateBaseDO.setModifyBy(UserUtils.getUserId());
        pageTemplateBaseDO.setModifyTime(LocalDateTime.now());
        pageTemplateBaseMapper.updateById(pageTemplateBaseDO);
        return pageTemplateBaseDO.getId();
    }

    @Override
    public PageBaseVO view(Long id) {
        PageTemplateBaseDO pageTemplateBaseDO = pageTemplateBaseMapper.selectById(id);
        return BeanUtil.convertBean(pageTemplateBaseDO, PageBaseVO.class);
    }

    @Override
    public PageTemplateBaseBO selById(Long id) {
        PageTemplateBaseDO pageTemplateBaseDO = pageTemplateBaseMapper.selectById(id);
        return BeanUtil.convertBean(pageTemplateBaseDO, PageTemplateBaseBO.class);
    }

    @Override
    public List<PageTemplateBaseBO> selById(Set<Long> ids) {
        List<PageTemplateBaseDO> pageTemplateBaseDOS = pageTemplateBaseMapper.selectBatchIds(ids);
        return JsonUtils.jsonToList(pageTemplateBaseDOS, PageTemplateBaseBO.class);
    }

    @Override
    public PageTemplateBaseBO selByPageCategory(PageCategoryEnum pageCategoryEnum) {
        if (pageCategoryEnum == null) {
            return null;
        }
        PageTemplateBaseDO pageTemplateBaseDO = pageTemplateBaseMapper.selectOne(new LambdaQueryWrapper<PageTemplateBaseDO>().eq(PageTemplateBaseDO::getCategory, pageCategoryEnum.getValue()));
        return BeanUtil.convertBean(pageTemplateBaseDO, PageTemplateBaseBO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeStatus(Long id, Integer status) {
        PageTemplateBaseDO pageTemplateBaseDO = new PageTemplateBaseDO();
        pageTemplateBaseDO.setId(id);
        pageTemplateBaseDO.setPublishStatus(status);
        pageTemplateBaseDO.setModifyTime(LocalDateTime.now());
        return pageTemplateBaseMapper.updateById(pageTemplateBaseDO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean del(Long id) {
        PageTemplateBaseDO pageTemplateBaseDO = pageTemplateBaseMapper.selectById(id);
        if (pageTemplateBaseDO == null) {
            return true;
        }
        pageTemplateModuleServiceImpl.delByPageId(id);
        return pageTemplateBaseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveToTemplate(PageToTemplateParam param, CurrentUser currentUser) {
        LogUtils.info("PageToTemplateParam >>>> {}", JsonUtils.toJsonStr(param));
        Long pageId = param.getPageId();
        DataUtils.trueThrowException(pageId == null, "页面Id不能为空!");
        PageBaseBO pageBaseBO = pageBaseServiceImpl.selById(pageId);
        DataUtils.trueThrowException(pageBaseBO == null, "未查询到当前页面数据!");
        List<PageModuleDO> pageModuleDOS = pageModuleServiceImpl.selByPageId(pageId);
        DataUtils.trueThrowException(Collections3.isEmpty(pageModuleDOS), "未查询到当前页面数据!");
        PageTemplateBaseParam templateBaseParam = BeanUtil.convertBean(pageBaseBO, PageTemplateBaseParam.class);
        if(StringUtils.isEmpty(templateBaseParam.getIndustry())){
            templateBaseParam.setIndustry(currentUser.getIndustry());
        }
        templateBaseParam.setCategory(param.getCategory());
        templateBaseParam.setTemplateType(param.getTemplateType());
        templateBaseParam.setTemplateImgUrl(param.getTemplateImgUrl());
        templateBaseParam.setTemplateName(param.getTemplateName());
        templateBaseParam.setDescription(param.getDescription());
        Long newBaseId = IdGenerator.getId();
        templateBaseParam.setId(newBaseId);
        getBean().add(templateBaseParam);
        //修改页面模板组件表
        List<PageTemplateModuleParam> pageTemplateModuleParams = JsonUtils.jsonToList(pageModuleDOS, PageTemplateModuleParam.class);
        if(Collections3.isNotEmpty(pageTemplateModuleParams)){
            pageTemplateModuleParams.stream().forEach(s->{
                s.setId(IdGenerator.getId());
                s.setPageId(newBaseId);
            });
            pageTemplateModuleServiceImpl.delByPageId(pageId);
            pageTemplateModuleServiceImpl.addList(pageTemplateModuleParams);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean loadTemplateToPage(TemplateToPageParam param, CurrentUser currentUser) {
        DataUtils.trueThrowException(param.getTemplateId() == null, "页面模板Id不能为空!");
        Long templateId = param.getTemplateId();
        if(param.getPageId()!=null){
            PageBaseBO pageBaseBO = pageBaseServiceImpl.selById(param.getPageId());
            if(pageBaseBO!=null){
                pageBaseServiceImpl.del(param.getPageId());
            }
        }
        if(templateId != Long.valueOf(GlobalConstant.tenantId)){
            PageTemplateBaseDO pageTemplateBaseDO = pageTemplateBaseMapper.selectById(templateId);
            DataUtils.trueThrowException(pageTemplateBaseDO == null, "未查询到模板页面数据!");
            List<PageTemplateModuleBO> pageTemplateModuleBOS = pageTemplateModuleServiceImpl.selByPageId(templateId);
            DataUtils.trueThrowException(Collections3.isEmpty(pageTemplateModuleBOS), "未查询到模板页面数据!");
            PageBaseParam baseParam = BeanUtil.convertBean(pageTemplateBaseDO, PageBaseParam.class);
            if(StringUtils.isEmpty(baseParam.getIndustry())){
                baseParam.setIndustry(currentUser.getIndustry());
            }
            baseParam.setCategory(pageTemplateBaseDO.getCategory());
            baseParam.setType(pageTemplateBaseDO.getTemplateType());
            baseParam.setPath("");
            baseParam.setTitle(pageTemplateBaseDO.getTitle());
            baseParam.setDescription(pageTemplateBaseDO.getDescription());
            Long newBaseId = IdGenerator.getId();
            baseParam.setId(newBaseId);
            pageBaseServiceImpl.add(baseParam);
            //修改页面模板组件表
            List<PageModuleParam> pageModuleParams = JsonUtils.jsonToList(pageTemplateModuleBOS, PageModuleParam.class);
            if(Collections3.isNotEmpty(pageModuleParams)){
                pageModuleParams.stream().forEach(s->{
                    s.setId(IdGenerator.getId());
                    s.setPageId(newBaseId);
                });
                pageModuleServiceImpl.addList(pageModuleParams);
            }
        }
        return true;
    }

    private PageTemplateBaseServiceImpl getBean() {
        return SpringBeanUtil.getBean(this.getClass());
    }


}